"""
-------------------------------------------------
  Author: hxy
  Date：2022-09-15 14:47
  Des：iot/temp1 初始化设备表
-------------------------------------------------
"""
from datetime import datetime

import psycopg2
import paho.mqtt.client as mqtt
import logging

_logger = logging.getLogger(__file__)
equip_list = []


class Sub():
    def __init__(self, topic, username, password, host, port, client_id):
        self.topic = topic
        self.client = mqtt.Client(client_id)
        self.client.username_pw_set(username, password)
        self.client.connect(host=host, port=port)
        self.client.on_connect = self.on_connect
        self.client.on_message = self.on_message
        self.client.loop_forever()

    def on_connect(self, client, userdata, flags, rc):
        rc = str(rc)
        if rc == '0':
            self.client.subscribe(self.topic)
        else:
            _logger.info(f'连接失败: 状态码为{rc}')

    def on_message(self, client, userdata, msg):
        try:
            data_list = eval(msg.payload.decode('utf-8'))
            if data_list:
                conn = psycopg2.connect(host='127.0.0.1', port=5432, user='odoo', password='odoo', database='iot')
                cur = conn.cursor()
                cabinet_code = data_list['Device_ID']
                sql_select = f"select * from iot_cabinet where code='{cabinet_code}'"
                print(sql_select)
                cur.execute(sql_select)
                rows = cur.fetchall()
                if len(rows) > 0:
                    pass
                else:
                    name = '配电柜' + cabinet_code
                    sql_insert = f"insert into iot_cabinet(name, is_deleted, code, create_datetime, update_datetime, warm_warning, warm_early_warning, v_early_warning) " \
                                 f"values('{name}', False, '{cabinet_code}', '{datetime.now()}', '{datetime.now()}', 90, 70, 0);"
                    print(sql_insert)
                    cur.execute(sql_insert)
                    conn.commit()
                cur.close()
                conn.close()
        except Exception as e:
            _logger.error(f'e: {e}')


Sub(topic='iot/temp1', username='emqx', password='public', host='39.98.122.153', port=1883, client_id='iot_sub_2')
